package com.shell;

import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
//import cn.hotool.core.io.IoUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;

public class SshUtil {

    private Vector<String> stdout;

    // 会话session
    Session session;

    public SshUtil(final String ipAddress, final String username, final String password, int port){
        try{
            JSch jsch = new JSch();
            session = jsch.getSession(username, ipAddress, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(100000);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    // 执行命令
    public int execute(final String command) throws IOException {
        int returnCode = 0;
        ChannelShell channel = null;
        PrintWriter printWriter = null;
        BufferedReader input = null;
        stdout = new Vector<>();
        try{
            channel = (ChannelShell) session.openChannel("shell");
            channel.connect();

            input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            printWriter = new PrintWriter(channel.getOutputStream());
            printWriter.println(command);
            printWriter.println("exit");
            printWriter.flush();
            System.out.println("The remote command is：");

            String line;
            while ((line = input.readLine()) != null){
                stdout.add(line);
                System.out.println(line);
            }
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }finally {
//            IOUtil.close(printWriter);
//            IOUtils.close(input);
            printWriter.close();
            input.close();
            if (channel != null){
                channel.disconnect();
            }
        }
        return returnCode;
    }

    // 断开链接
    public void close(){
        if (session != null){
            session.disconnect();
        }
    }

    // 执行命令获取执行结果
    public String  executeForResult(String command) {
        StringBuilder sb = new StringBuilder();
        try {
            execute(command);
            for (String str : stdout){
                sb.append(str);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        String cmd = "cd /data/innohive/portal/ip005/web-server\n" +
                " sh web-server.sh stop\n" +
                "sh web-server.sh start";
        SshUtil execut = new SshUtil("8.134.19.139", "root", "Innohive8888", 22);
        // 执行命令
        String result =execut.executeForResult(cmd);
        System.out.println(result);
        execut.close();
    }




}
